import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:mi_mang_flutter/config/configs.dart';
import 'package:mi_mang_flutter/generated/l10n.dart';
import 'package:mi_mang_flutter/manager/app_manager.dart';
import 'package:mi_mang_flutter/page/public/splash_page.dart';
import 'package:mi_mang_flutter/provider/locale_provider.dart';
import 'package:mi_mang_flutter/provider/theme_provider.dart';
import 'package:mi_mang_flutter/provider/user_provider.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:provider/provider.dart';
import 'package:custom_widgets/custom_localizations.dart';

Future main() async {
  if (!Configs.DEBUG) {
    // 发布模式下需要禁用该项
    Provider.debugCheckInvalidValueType = null;
  }

  // 需要确保[WidgetsFlutterBinding]的初始化
  WidgetsFlutterBinding.ensureInitialized();
  setCustomErrorPage();
  _setTargetPlatformForDesktop();
  // 由于SpUtil未初始化，所以MaterialApp获取的为默认主题配置，这里同步一下。
  await AppManager.initSp();

  FlutterError.onError = (FlutterErrorDetails details) async {
    Zone.current.handleUncaughtError(details.exception, details.stack!);
  };
  runZonedGuarded(() {
    /// 强制竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitDown,
      DeviceOrientation.portraitUp,
    ]).then((_) {
      //异常上报
      FlutterBugly.postCatchedException(
        () {
          runApp(MyApp());
        },
        debugUpload: !Configs.DEBUG,
        // 过滤花括号包裹的, 包含code字符串与msg字符串的异常(不上传bugly)
        filterRegExp: "{.*\"code\".*.*\"msg\".*}",
        // handler: (FlutterErrorDetails error) {
        //   print("bugly异常打印: ${error.exception.toString()}");
        // },
      );
      // Android设备透明状态栏
      if (Platform.isAndroid) {
        // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
        SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
        );
        SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
      }
    });
  }, (Object error, StackTrace stack) {
    //zone内异常handle直接上报
    // FlutterBugly.uploadException(detail: error.toString(), message:stack.toString());
    debugPrint("Main方法拦截的异常" + error.toString());
    debugPrint(stack.toString());
  });
}

void setCustomErrorPage() {
  ErrorWidget.builder = (FlutterErrorDetails flutterErrorDetails) {
    debugPrint(flutterErrorDetails.toString());
    return Center(child: Text("页面异常,可前往设置-反馈"));
  };
}

/// If the current platform is desktop, override the default platform to
/// a supported platform (iOS for macOS, Android for Linux and Windows).
/// Otherwise, do nothing.
void _setTargetPlatformForDesktop() {
  TargetPlatform? targetPlatform;
  if (Platform.isMacOS) {
    targetPlatform = TargetPlatform.iOS;
  } else if (Platform.isLinux || Platform.isWindows) {
    targetPlatform = TargetPlatform.android;
  }
  if (targetPlatform != null) {
    debugDefaultTargetPlatformOverride = targetPlatform;
  }
}

class MyApp extends StatelessWidget {
  MyApp() {
    AppManager.initRouter();
    // 初始化屏幕适配
    AppManager.initScreenUtil();
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    // 添加全局状态管理
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => UserProvider()),
        ChangeNotifierProvider(create: (_) => ThemeProvider()),
        ChangeNotifierProvider(create: (_) => LocaleProvider()),
      ],
      child: Consumer2<ThemeProvider, LocaleProvider>(
        builder: (_, themeModel, localeModel, child) {
          return MaterialApp(
            title: '米茫',
            // 右上角显示一个debug的图标
            debugShowCheckedModeBanner: false,
            theme: themeModel.themeData(),
            darkTheme: themeModel.themeData(platformDarkMode: true),
            locale: localeModel.locale,
            // 该处原本可以使用以下注释的代码, 由于下拉刷新组件不支持,所有使用下面这种方式
            // supportedLocales: S.delegate.supportedLocales,
            supportedLocales: localeModel.supportedLocales,
            localizationsDelegates: const [
              Custom_Localizations.delegate,
              S.delegate,
              GlobalCupertinoLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              DefaultCupertinoLocalizations.delegate,
            ],
            builder: themeModel.buildMediaQuery(),
            home: SplashPage(),
            onGenerateRoute: AppManager.router!.generator,
            navigatorObservers: [
              BotToastNavigatorObserver(),
            ],
            navigatorKey: AppManager.navigatorKey,
          );
        },
      ),
    );
  }
}
